package userlogic

import (
	"common/dao/model"
	"context"
	"errors"
	"gorm.io/gorm"

	"OemServer/internal/svc"
	"OemServer/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type DisableLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDisableLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DisableLogic {
	return &DisableLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DisableLogic) Disable(in *pb.ChangeDisable) (*pb.Emp, error) {
	// todo: add your logic here and delete this line
	if in.Status != 1 && in.Status != 2 {
		return nil, errors.New("status 1 or Status 2")
	}
	if in.Uuid == "" {
		return nil, errors.New("uuid empty")
	}
	db := l.svcCtx.DB
	table1 := db.Table(model.TableNameUser)
	table2 := db.Table(model.TableNameUserRole)
	err := table1.Transaction(func(tx *gorm.DB) error {
		var (
			user model.User
			role model.UserRole
		)
		if err := tx.First(&user, "uuid = ?", in.Uuid).Error; err != nil {
			return err
		}
		if user.RoleUUID == "" {
			return errors.New("user.RoleUUID is empty")
		}
		if user.IsAdmin == 1 {
			return errors.New("无法操作超级用户")
		}
		if in.Status == 1 {
			if err := table2.First(&role, "uuid = ?", user.RoleUUID).Error; err != nil {
				return err
			}
			if role.RoleStatus == 2 {
				return errors.New("账号绑定的权限已被禁用")
			}
			user.Disable = 1
		} else if in.Status == 2 {
			user.Disable = 2
		}
		if err := tx.Save(&user).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}

	return &pb.Emp{}, nil
}
